<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\general\LihuaCity;
use app\common\model\goods\LihuaStock;
use app\common\model\LihuaOrder;
use app\common\model\LihuaRefund; //退单记录
use app\common\model\LihuaOrderGoods;
use app\common\model\LihuaUserbonus;
use app\common\model\LihuaHongbao;
use app\common\model\LihuaActivity; //城市活动表
use app\common\model\LihuaOrderActivity; //订单活动表
use app\common\model\LihuaVouchers; //现金抵用券
use app\admin\model\User;
use fast\Http;
use think\Db;
use think\Exception;
use think\Validate;
use think\Log;

/**
 * 订单
 */
class Order extends Api
{
    protected $noNeedLogin = ['*', 'getsevendays', 'getCartOrderInfo', 'refuseapply', 'cancel_admin', 'refuse_financial', 'get_yeardata', 'office_list'];
    protected $noNeedRight = ['*'];

	// 小程序分享领红包接口
	public function xcx_shear()
	{
	    $oid = $this->request->request('oid');//此oid实为订单号sn
	    $uid = $this->request->request('uid');//用户uid
	    $nickname = $this->request->request('nickname');//
	    $avatarurl = $this->request->request('avatarurl');//
	    if (!$oid || !$uid ) $this->error('参数错误');
	    $order = LihuaOrder::getBySn($oid);
	    if (!$order) $this->error('非法操作');
	    if ($order->create_time < time() - 2592000) $this->error('此分享红包已失效');//下单30天后失效
	
	    $wxuid   = 0;//微信用户id
	    $isget   = 0;//当前用户是否领取红包
	    $getcnt  = 0;//当前用户今日领取红包次数
	    $isover  = 0;//当前订单红包是否领完
	    $info    = [];//当前用户领取当前红包信息
	    $list    = [];//当前订单红包领取列表
		// $mybonus = [];//当前用户领取的红包
	    // $login  = Cookie::get('lh_h5login');
	    // if ($login) {
	        // $login = $this->io_aes_decrypt($login);
	        // list($uid, $mobile) = explode('|', $login);
	        if ($uid) {
	            // $wxuser = LihuaWxuser::get(['user_id' => $uid]);
	            // if (!$wxuser) {//未绑定微信则重新授权登录
	                // Cookie::delete('lh_h5login');
	                // $this->redirect($this->request->domain() . '/wxoauth.php?state=' . $oid); exit;
	            // }

                //用户无法领取自己的订单
                if( $order->user_id == $uid ) $this->error('您无法领取自己的订单分享');
	            $getcnt = LihuaHongbao::where(['user_id' => $uid, 'start_date' => date('Y-m-d')])->count();

	            // 该订单红包领取列表
	            $list = (array)LihuaHongbao::where('order_id', $order->id)->select();
				foreach ($list as $kk => $v) {
					$list[$kk]['reach'] = round($v['reach'], 2);
					$list[$kk]['reduce'] = round($v['reduce'], 2);
				}
	            foreach ($list as $k => $v) {
	                if ($v['user_id'] == $uid) {
	                    $isget = 1;//当前用户已领取过round($v['reduce'], 2)
	                    $info  = ['reach' => round($v['reach'], 2), 'reduce' => round($v['reduce'], 2), 'end_date' => $v['end_date']];
						$this->success('红包已经发送到您的丽华账户', ['list'=> $list, 'info'=> $info] );
					}
	            }
	            if (count($list) == 19) {
					$isover = 1;
					$this->error('当前红包领取已经达到上限', ['list'=> $list, 'info'=> ''] );
				}
	
	            // 用户未领取红包则领取
	            if ($getcnt < 5 && !$info && $isover == 0) {
	                $moneyArr = [
	                    '1', '1', '1', '2', '2', '2',
	                    '2', '2', '3', '3', '3', '3',
	                    '4', '4', '5', '5', '6', '6',
						'7', '8', '9', '10'
	                ];
	                $i = mt_rand(0, 21);
	                $money = $moneyArr[$i];
	                if ($money >= 4 && $money <= 6) {
	                    $reach = $money * 12;
	                } elseif ($money > 6) {
	                    $reach = $money * 12;
	                } else {
	                    $reach = 0;
	                }
	
	                $hb = LihuaHongbao::create([
	                    'order_id'   => $order->id,
	                    'order_sn'   => $order->sn,
	                    'user_id'    => $uid,
	                    'nickname'   => $nickname,
	                    'avatar'     => $avatarurl,
	                    'reach'      => $reach,
	                    'reduce'     => $money,
	                    'start_date' => date('Y-m-d'),
	                    'end_date'   => date('Y-m-d', strtotime('+3 day')),
	                ]);
	                array_push($list, $hb->toArray());
	                $info = ['reach' => $reach, 'reduce' => $money, 'end_date' => $hb->end_date];
	                LihuaUserbonus::create([
	                    'city_id'    => 0,
	                    'user_id'    => $uid,
	                    'bonus_id'   => 0,
	                    'name'       => '分享红包',
	                    'type'       => 9,
	                    'reach'      => $reach,
	                    'reduce'     => $money,
	                    'des'        => '',
	                    'start_date' => $hb->start_date,
	                    'end_date'   => $hb->end_date,
	                ]);
					$this->success('红包已经发送到您的丽华快餐账户', ['list'=> $list, 'info'=> $info] );
	            }else{
					$this->error('每天只能领取5个分享红包', ['list'=> $list, 'info'=> '']);
				}
	        } else {
	            // Cookie::delete('lh_h5login');
	            $this->error('非法操作');
	        }
	    //} 
	    
	    // return $this->fetch();
	}
	
    /**
     * 提交订单
     *
     * @ApiMethod   (POST)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求Token，游客不传")
     * @ApiParams   (name="platform", type="string", required=true, description="平台，值为app或xcx")
     * @ApiParams   (name="city_id", type="int", required=true, description="城市ID")
     * @ApiParams   (name="pay_type", type="int", required=true, description="支付方式：1=支付宝支付，2=微信支付，3=丽华钱包，4=货到付款，5=贵宾卡支付")
     * @ApiParams   (name="addr_id", type="int", required=true, description="收货地址ID，会员必要")
     * @ApiParams   (name="consignee", type="string", required=true, description="收货人，游客必要")
     * @ApiParams   (name="mobile", type="string", required=true, description="收货手机，游客必要")
     * @ApiParams   (name="name", type="string", required=true, description="地址名称，游客必要")
     * @ApiParams   (name="house_num", type="string", required=true, description="地址门牌，游客必要")
     * @ApiParams   (name="lng", type="string", required=true, description="地址经度，游客必要")
     * @ApiParams   (name="lat", type="string", required=true, description="地址纬度，游客必要")
     * @ApiParams   (name="goods_nums", type="string", required=true, description="商品ID及数量键值对JSON字符串")
     * @ApiParams   (name="bonus_id", type="int", required=false, description="用户红包ID，默认0不使用红包")
     * @ApiParams   (name="deliver_time", type="string", required=true, description="送餐时间")
     * @ApiParams   (name="tableware", type="int", required=false, description="餐具：0=不需要，1=需要")
     * @ApiParams   (name="invo_id", type="int", required=false, description="发票ID，默认0不需要发票")
     * @ApiParams   (name="invo_type", type="int", required=false, description="发票类型，游客可传")
     * @ApiParams   (name="invo_title", type="string", required=false, description="发票抬头，游客可传")
     * @ApiParams   (name="taxno", type="string", required=false, description="发票税号，游客可传")
     * @ApiParams   (name="remark", type="string", required=false, description="订单备注")
     * @ApiReturn   ({"code":1,"msg":"OK","time":"1567010784","data":{"order_id":"1","sn":"190925460938715"}})
     */
    public function post()
    {
        $this->request->filter('trim,strip_tags');
        $city_id        = (int)$this->request->post('city_id', 0);
        $platform       = strtolower($this->request->post('platform'));
        $pay_type       = $this->request->post('pay_type', 0);//支付方式
        $tableware      = $this->request->post('tableware', 0);//需要餐具
        $goods_nums     = $this->request->post('goods_nums', '');//商品及数量
        $deliver_time   = $this->request->post('deliver_time', '');//送餐时间
        $remark         = $this->request->post('remark', '');//备注信息
        $doorshop       = (int)$this->request->post('doorshop', 0);//是否选择到店自取
        $use_half_Free  = (int)$this->request->post('use_half_free', 1);//是否选择支持活动优惠
        $use_sales_free = (int)$this->request->post('use_sales_free', 1);//是否选择支持活动优惠
        $city_enough    = (int)$this->request->post('city_enough', 1);//是否使用城市满减的活动0不使用，1使用
        $vouchers_sn    = $this->request->post('vouchers_sn', '');//现金抵扣券码
        $deliver_fee    = $this->request->post('deliver_fee', 0);//最新的送餐费

        if (!$city_id) $this->error('非法操作');
        if (!in_array($platform, ['app', 'xcx'])) $this->error('非法操作');
        // if (!in_array($pay_type, [1, 2, 3, 4, 5]))   $this->error('非法操作');

        if (!$goods_nums)   $this->error('请选择商品');
        if (!$deliver_time) $this->error('请选择送餐时间');
        if (mb_strlen($remark) > 80) $this->error('订单备注请在80个字以内');

        $goods_nums = json_decode($goods_nums, true);
        if (json_last_error()) $this->error('商品数据异常');

        $addr  = [];
        $bonus = ['id' => 0, 'name' => '', 'fee' => 0];
        $invo  = ['type' => 0, 'title' => '', 'taxno' => ''];
        $bonus_reach = 0;

        //现金券码去空格
        $vouchers_sn = str_replace(" ",'',$vouchers_sn);

        //现金券码转大写
        $vouchers_sn = strtoupper($vouchers_sn);
        $vouchers_info = [ 'id'=>0, 'price'=>0, 'sn'=>'' ];
        //查询出现金券记录
        if($vouchers_sn!=''){
            $vouchers_res = LihuaVouchers::where([ 'sn'=>$vouchers_sn])->find();
            if(!!$vouchers_res){
                if($vouchers_res['status']==0){
                    $vouchers_info = $vouchers_res;
                }
            }
        }

        if ($this->token) {
            $user_id  = $this->auth->id;
            $addr_id  = $this->request->post('addr_id', 0);//用户地址id
            $bonus_id = $this->request->post('bonus_id', 0);//用户红包id
            $invo_id  = $this->request->post('invo_id', 0);//用户发票id
            
            if ($addr_id > 0) {
                $addr = \app\common\model\LihuaUseraddr::where(['id' => $addr_id, 'user_id' => $user_id])->find();
                if (!$addr) $this->error('送餐地址已失效');

                //因为地图可能存在改动片区的情况，所以用户地址表中的分店信息不可信
                /**
                  *  如果地址有效则判断当前地址所对应的门店是否处于正常状态
                  *  $store = \app\common\model\general\LihuaStore::where([ 'id'=> $addr['store_id'], 'status'=> 1 ])->find();
                  *  if(!$store) { $addr['store_id'] = ''; }
                  *  if($store['status']==0) { $addr['store_id'] = ''; }
                  *  if($addr['store_id']==''){
                  *      //重新获取对应门店
                  *      $store = \app\common\model\general\LihuaStore::getPointStore($city_id, $addr['lng'], $addr['lat']);
                  *      if ($store['id'] == 0) $this->error('对应门店已经休假,请选择其他收餐地址');
                  *      $addr['store_id'] = $store['id'];
                  *      $addr['store_name'] = $store['name'];
                  *  }
                **/
                //重新获取对应门店
                $store = \app\common\model\general\LihuaStore::getPointStore($city_id, $addr['lng'], $addr['lat']);
                if ($store['id'] == 0) $this->error('对应门店已经休假,请选择其他收餐地址');
                $addr['store_id'] = $store['id'];
                $addr['store_name'] = $store['name'];

            } else {
                //如果是到店自取的情况
                if($doorshop==1){
                    $consignee = $this->request->post('consignee');
                    $mobile    = $this->request->post('mobile');
                    $name      = $this->request->post('name');
                    $house_num = $this->request->post('house_num');
                    $lng       = $this->request->post('lng');
                    $lat       = $this->request->post('lat');
                    if (!$mobile || !$name || !$house_num || !is_numeric($lng) || !is_numeric($lat)) $this->error('地址错误');
                    if (!Validate::regex($mobile, "^1\d{10}$")) $this->error('手机号格式错误');
                    $store = \app\common\model\general\LihuaStore::getPointStore($city_id, $lng, $lat);
                    if ($store['id'] == 0) $this->error('地址不在配送范围内');
                    $addr = [
                        'city_id'    => $store['city_id'],
                        'store_id'   => $store['id'],
                        'store_name' => $store['name'],
                        'consignee'  => $consignee,
                        'mobile'     => $mobile,
                        'name'       => $name,
                        'house_num'  => $house_num,
                        'lng'        => $lng,
                        'lat'        => $lat,
                        'address'    => "",
                    ];
                }else{
                    $this->error('请选择送餐地址');
                }
            }
            /**
             * 设置使用的红包
             * 1、必须登录的情况下
             * 2、必须现金抵扣券码没有使用的情况下
            */
            if ($bonus_id > 0 && $vouchers_info['id']==0 ) {
                $row = LihuaUserbonus::where(['id' => $bonus_id, 'user_id' => $user_id])->find();
                if ($row && $row['status'] == 0 && $row['end_date'] >= date('Y-m-d')) {
                    $bonus = ['id' => $row['id'], 'name' => $row['name'], 'fee' => round($row['reduce'], 2)];
                    $bonus_reach = $row['reach'];
                } else {
                    $this->error('红包已失效');
                }
            }
            if ($invo_id > 0) {
                $row = \app\common\model\LihuaUserinvo::where(['id' => $invo_id, 'user_id' => $user_id])->find();
                if ($row) {
                    $invo = ['type' => $row['type'], 'title' => $row['title'], 'taxno' => $row['taxno']];
                } else {
                    $invo_id = 0;
                }
            }
        } else {
            $this->error('请先登录账号');
            $user_id = 0;
            //游客送餐地址信息
            $consignee = $this->request->post('consignee');
            $mobile    = $this->request->post('mobile');
            $name      = $this->request->post('name');
            $house_num = $this->request->post('house_num');
            $lng       = $this->request->post('lng');
            $lat       = $this->request->post('lat');
            if (!$mobile || !$name || !$house_num || !is_numeric($lng) || !is_numeric($lat)) $this->error('地址错误');
            if($doorshop==0){
                $len = mb_strlen($consignee);
                if ($len < 2 || $len > 12 || !Validate::is($consignee, 'chs')) $this->error('姓名只允许2~12个汉字');
            }
            if (!Validate::regex($mobile, "^1\d{10}$")) $this->error('手机号格式错误');

            $store = \app\common\model\general\LihuaStore::getPointStore($city_id, $lng, $lat);
            if ($store['id'] == 0) $this->error('地址不在配送范围内');

            $addr = [
                'city_id'    => $store['city_id'],
                'store_id'   => $store['id'],
                'store_name' => $store['name'],
                'consignee'  => $consignee,
                'mobile'     => $mobile,
                'name'       => $name,
                'house_num'  => $house_num,
                'lng'        => $lng,
                'lat'        => $lat,
                'address'    => "",
            ];

            //游客发票信息
            $invo_type  = $this->request->post('invo_type', 0);
            $invo_title = $this->request->post('invo_title', '');
            $invo_taxno = $this->request->post('taxno', '');
            if (!in_array($invo_type, [0,1,2,3])) $this->error('发票类型错误');
            if (mb_strlen($invo_title) > 50)      $this->error('发票抬头过长');
            if (mb_strlen($invo_taxno) > 30)      $this->error('发票税号过长');

            $invo = [
                'type'  => $invo_type,
                'title' => $invo_title,
                'taxno' => $invo_taxno,
            ];
        }

        $user_id = 0;
        if ($this->token) { $user_id = $this->auth->id; }

        //商品信息
        $goods = \app\common\model\goods\LihuaGoods::getCartGoodsList($addr['store_id'], $goods_nums, $user_id);
        if ($goods['goods_nums'] != $goods_nums) $this->error('有商品已失效，请重新选择');
        if (!$goods['alone_sale'])       $this->error('请选择一份主食，配餐商品单点不送');
        if ($goods['lack_goods']['ids']) $this->error(join('、', $goods['lack_goods']['names']) . ' 库存不足');

        //城市信息
        $city = LihuaCity::getCityInfo($addr['city_id']);

        $city['deliver_fee'] = $deliver_fee;

        //首先判断到店自取的时间是否已经过了营业时间
        if($doorshop==1){
            if( !(( $deliver_time >= $city['am_time'][0] && $deliver_time <= $city['am_time'][1] ) || ( $deliver_time >= $city['pm_time'][0] && $deliver_time <= $city['pm_time'][1] ))  ){
                if( $deliver_time >= $city['am_time'][1] && $deliver_time <= $city['pm_time'][0] ){
                    $deliver_day_time = strtotime(date('Y-m-d ') . $city['pm_time'][0] . ':00');
                    $fast_deliver_time = bcadd($deliver_day_time, (int)$city['fasttime'] * 60, 0);
                    $deliver_time = date("H:i", $fast_deliver_time);
                }
                if($deliver_time <= $city['am_time'][0]){
                    $deliver_day_time = strtotime(date('Y-m-d ') . $city['am_time'][0] . ':00');
                    $fast_deliver_time = bcadd($deliver_day_time, (int)$city['fasttime'] * 60, 0);
                    $deliver_time = date("H:i", $fast_deliver_time);
                }
            }
        }
        
        if ($goods['goods_amount'] < $city['min_price']) $this->error('商品起送价￥' . $city['min_price']);

        //判断商品金额是否满足红包满减金额
        if ($bonus_reach > 0 && $goods['goods_amount'] < $bonus_reach) $this->error('非法操作');

        /**
         * 城市满减 , 客户端如果传过来需要使用城市满减的活动，则计算减免金额
        */
        $enough = ['name'=>'','reduce'=>0];
        if($city_enough==1){
            $enough = LihuaCity::countEnough($city['enough'], $goods['goods_amount']);
            // 当前使用了城市满减的活动
            // if($bonus_reach>0 && $enough['reduce']>0){
            //     //清空红包
            //     $bonus = ['id' => 0, 'name' => "", 'fee' => 0];
            // }
        }

        //订单号
        $sn = date('ym') . sprintf("%05d", mt_rand(1, 99999)) . date('d') . sprintf("%05d", mt_rand(1, 99999));
        $actfree = [
            'half'          => [], // 第二份半价
            'sales'         => [], // 促销商品
            'half_free'     => 0,  // 第二份半价优惠费用
            'sales_free'    => 0,  // 促销商品优惠会用
            'half_mutex'    => 0,  // 半价活动是否互斥
            'sales_mutex'   => 0,  // 半价活动是否互斥
            'enough_reduce' => 0,  // 满减优惠金额
            'half_act_id'   => 0,  // 第二份半价活动ID
            'sales_act_id'  => 0,  // 限时促销活动ID
        ];

        /***
         * 计算城市活动优惠
         * 1、未使用现金抵扣券
         * 2、用户登录的情况下
         *  */
        if ( $this->token && $vouchers_info['id']==0 ) {
            $user_id  = $this->auth->id;
            $actfree = LihuaActivity::computingOffers($city_id, $goods, $user_id, $use_half_Free, $use_sales_free, $addr['store_id']);
            if( $actfree['half_free']>0 || $actfree['sales_free']>0 ) { //如果第二份半价和促销商品有优惠则不能使用满减优惠
                if($actfree['half_mutex']==1 && $actfree['half_free']>0){ //活动互斥的情况下才会将满减的优惠删除
                    $enough['reduce'] = 0;
                    // $bonus['fee'] = 0;
                    // $bonus['name'] = '';
                }
                if($actfree['sales_mutex']==1 && $actfree['sales_free']>0){ //活动互斥的情况下才会将满减的优惠删除
                    $enough['reduce'] = 0;
                    // $bonus['fee'] = 0;
                    // $bonus['name'] = '';
                }
            }
        }

        //判断当天是否已经享受了满减的活动，如果已经享受了，就没发享受
        /**
         * $user_id, 
         * **/
        $reduce_checkval = $this->check_reduce( $user_id, $city, $enough['reduce'] );
    

		//vip支付订单，需要免配送费
		if($pay_type==5){
			$city['deliver_fee'] = 0;
		}
		
        //选择订单自取，免运费
        if($doorshop==1){
            $city['deliver_fee'] = 0;
        }

        //北京地区 12:00到13：30 免配送费
        // if( $deliver_time>="12:00" && $deliver_time<="13:30" && $city_id==1 ){
        //     $city['deliver_fee'] = 0;
        // }
		
        //订单金额
        $discount = abs(round($actfree['half_free'] + $actfree['sales_free'] + $enough['reduce'] + $bonus['fee'] + $vouchers_info['price'], 2));//已优惠

        $amount_dis = round($goods['goods_amount'] - $discount, 2);
        //城市设置了满额免运费
        if($city['feeprice']>0){
            if($amount_dis>=$city['feeprice']){
                $city['deliver_fee'] = 0;
            }
        }
        //城市满额免餐盒费
        if($city['feepacking']>0){
            if($amount_dis>=$city['feepacking']){
                $goods['packing_fee'] = 0;
            }
        }

        $original_amount = round($goods['goods_amount'] + $goods['packing_fee'] + $city['deliver_fee'], 2);
        $order_amount = bcsub($original_amount, $discount, 2);
		
        if ($order_amount < 0) $order_amount = 0;

        if( $city_id == 6 || $city_id == 2 || $city_id == 3 ) {

        }else{
            if ($order_amount < $city['min_price']) $this->error('订单起送价￥' . $city['min_price']);
        }
        
        /**送达时间处理****
         * 1、前提条件是非到店自取
         * 2、如果送达时间小于当前时间+30分钟，则送达时间修改为当前时间+30分钟 
         * 3、如果送达时间大于当前时间+30分钟，则不做处理
         * **/
        if($doorshop!=1){
            $deliver_day_time = strtotime(date('Y-m-d ') . $deliver_time . ':00');
            $now_time_them = time();
            $fast_deliver_time = $now_time_them + (int)$city['fasttime'] * 60;
            if($deliver_day_time<$fast_deliver_time){
                $deliver_time = date("H:i", $fast_deliver_time);
            }
        }

        //订单数据
        $data = [
            'sn'                => $sn,
            'user_id'           => $user_id,
            'city_id'           => $addr['city_id'],
            'city_name'         => $city['city_name'],
            'store_id'          => $addr['store_id'],
            'store_name'        => $addr['store_name'],
            'consignee'         => $addr['consignee'],
            'mobile'            => $addr['mobile'],
            'address'           => $addr['address'] . $addr['name'] . $addr['house_num'],
            'lng'               => $addr['lng'],
            'lat'               => $addr['lat'],
            'packing_fee'       => $goods['packing_fee'],
            'deliver_fee'       => $city['deliver_fee'],
            'enough_name'       => $enough['name'],//满减名称
            'enough_fee'        => $enough['reduce'],//满减金额
            'bonus_name'        => $bonus['name'],//红包名称
            'bonus_fee'         => $bonus['fee'],//红包金额
            'vouchers_fee'      => $vouchers_info['price'],//现金抵扣券
            'vouchers_sn'       => $vouchers_info['sn'],//现金抵扣券编号
            'deliver_time'      => date('Y-m-d ') . $deliver_time . ':00',
            'tableware'         => $tableware,
            'invo_type'         => $invo['type'],//发票类型
            'invo_title'        => $invo['title'],//发票抬头
            'invo_taxno'        => $invo['taxno'],//发票税号
            'remark'            => $remark,//备注
            'goods_amount'      => $goods['goods_amount'],
            'original_amount'   => $original_amount,//商品费+餐盒费+送餐费
            'order_amount'      => $order_amount,//商品费+餐盒费+送餐费-满减费-红包费
            'discount'          => $discount,//满减费+红包费
            'platform'          => $platform,
            'pay_type'          => $pay_type,
            'add_time'          => date('Y-m-d H:i:s'),
            'status'            => ($pay_type == 4 || $pay_type == 5) ? 2 : 1,//1待支付，货到付款直接进入2待确认
            'doorshop'          => $doorshop ,  //是否到店自取
        ];

        //北京地区需要最终支付价格大于起送价才能配送
        if( $city_id == 1 ) {
            $min_post_price = $order_amount - $goods['packing_fee'] - $city['deliver_fee'];
            if($min_post_price < $city['min_price']) $this->error('商品起送价￥' . $city['min_price']);
        }

        //上海地区享受活动后，最终支付价格需要大于起送价格
        if( $city_id == 2 ){
            $act_frees = bcadd($actfree['half_free'], $actfree['sales_free']);
            if($act_frees>0){//说明享受了优惠活动
                if($order_amount < $city['min_price']) $this->error('商品起送价￥' . $city['min_price']);
            }
        }

        //常州地区，起送价规则
        if( $city_id == 3 ){
            $min_post_price = 0;
            $min_post_price = bcadd($order_amount, $enough['reduce']);
            $min_post_price = bcadd($min_post_price, $bonus['fee']);
            $min_post_price = bcadd($min_post_price, $vouchers_info['price']);
            if($min_post_price < $city['min_price']) $this->error('商品起送价￥' . $city['min_price']);
        }

        if($doorshop==1) $data['address'] = '[自取单]'.$data['address'];

        //黑名单处理
        if($addr['mobile']=='13636532627'){
            $this->error('您的账号存在异常');
        }
        $user_info = User::where([ 'id' => $user_id ])->find();
        if($user_info['mobile']=='13636532627'){
            $this->error('您的账号存在异常');
        }

        //创建订单
        $order_id = 0;
        Db::startTrans();
        try {
            $order = LihuaOrder::create($data);
            Db::commit();
            $order_id = $order->id;
            //生成订单享受到的活动记录表half_free
            if($use_half_Free==1 && $actfree['half_free']>0){
                //活动互斥的情况下才会将满减的优惠删除
                $has = LihuaOrderActivity::where([ 'order_sn'=> $sn, 'type'=> 0 ])->count();
                if($has==0){
                    //支付状态
                    $paystatus = 0;
                    if($data['status']>=2) $paystatus = 1;
                    foreach ($actfree['half_act_id'] as $k => $free) {
                        foreach ($free as $k2 => $free2) {
                            if($free2>0){
                                //第二份半价type为0
                                $actData = [
                                    'order_sn'        => $sn,
                                    'type'            => 0,
                                    'activity_id'     => $k2,
                                    'user_id'         => $user_id,
                                    'discount'        => $free2,
                                    'createtime'      => date('Y-m-d H:i:s'),
                                    'name'            => $actfree['half_act_name'][$k][$k2],   //活动名称
                                    'paystatus'       => $paystatus,   //支付状态
                                ];
                                LihuaOrderActivity::create($actData);
                            }
                        }
                    }
                }
            }
            if($use_sales_free==1 && $actfree['sales_free']>0){ //活动互斥的情况下才会将满减的优惠删除
                $has = LihuaOrderActivity::where([ 'order_sn'=> $sn, 'type'=> 1 ])->count();
                if($has==0){
                    //支付状态
                    $paystatus = 0;
                    if($data['status']>=2) $paystatus = 1;
                    //限时促销type为1
                    foreach ($actfree['sales_act_id'] as $k => $free) {
                        foreach ($free as $k2 => $free2) {
                            if($free2>0){
                                $actData = [
                                    'order_sn'        => $sn,
                                    'type'            => 1,
                                    'activity_id'     => $k2,
                                    'user_id'         => $user_id,
                                    'discount'        => $free2,
                                    'createtime'      => date('Y-m-d H:i:s'),
                                    'name'            => $actfree['sales_act_name'][$k][$k2],   //活动名称
                                    'paystatus'       => $paystatus,   //支付状态
                                ];
                                LihuaOrderActivity::create($actData);
                            }
                        }
                    }
                }
            }
        } catch (Exception $e) {
            Db::rollback();
            $this->error('提交失败，请尝试重新提交');
        }

        //更新红包已使用
        if ($bonus['id'] > 0) {
            LihuaUserbonus::update(['status' => 1, 'order_sn' => $sn], ['id' => $bonus['id']]);
        }

        //商品减库存
        if ($goods['goods_stocks']) {
            foreach ($goods_nums as $k => $v) {
                if (isset($goods['goods_stocks'][$k])) {
                    LihuaStock::where(['goods_id' => $k, 'store_id' => $addr['store_id']])->setDec('num', $v);
                }
            }
        }

        //保存商品信息
        $orderGoods = [];
        //这里需要判断如果没有餐盒费

        foreach ($goods['goods'] as $k => $v) {
            if($goods['packing_fee']==0){
                $v['box_fee'] = 0;
            }
            $orderGoods[] = [
                'order_id'    => $order_id,
                'order_sn'    => $sn,
                'city_id'     => $addr['city_id'],
                'store_id'    => $addr['store_id'],
                'user_id'     => $user_id,
                'goods_id'    => $v['id'],
                'name'        => $v['name'],
                'short_name'  => $v['short_name'],
                'description' => $v['description'],
                'price'       => $v['price'],
                'pic'         => $v['pic'],
                'num'         => $v['num'],
                'num_price'   => $v['num_price'],
                'box_fee'     => $v['box_fee'],
                'create_date' => date('Y-m-d'),
            ];
        }
        if ($orderGoods) LihuaOrderGoods::insertAll($orderGoods);

        $this->success('OK', ['order_id' => $order_id, 'sn' => $sn]);
    }

    //计算订单能享受到的满减
    public function check_reduce($user_id, $city, $enough_reduce ){
        if($city['city_id']==1){
            // 每餐只能享受一次满减
            // 查询
            
            return $enough_reduce;
        }else{
            return $enough_reduce;
        }
    }


    /**
     * 绑定云闪付tn
     */
    public function unionpay_tn(){
        $sn = $this->request->request('sn', '');//订单sn
        $tn = $this->request->request('tn', '');//银联订单tn
        if ( !$sn || ! $tn) $this->error('参数错误');
        $order = LihuaOrder::getBySn($sn);
        if (!$order) $this->error('非法操作');
        $order->unionpay_tn = $tn;
        $s = $order->save();
        $this->success('OK', $s);
    }

    //获取年度销售额统计
    public function get_yeardata(){
		$AllOrderAmount_2019 = LihuaOrder::where(['status' => array('egt',2), 'add_time' => ['like', '%2019%'] ])->sum('order_amount');
		$AllOrderAmount_2020 = LihuaOrder::where(['status' => array('egt',2), 'add_time' => ['like', '%2020%'] ])->sum('order_amount');
        $AllOrderAmount_2021 = LihuaOrder::where(['status' => array('egt',2), 'add_time' => ['like', '%2021%'] ])->sum('order_amount');
        $this->success('OK', [
            'd_2019' => $AllOrderAmount_2019,
            'd_2020' => $AllOrderAmount_2020,
            'd_2021' => $AllOrderAmount_2021,
        ] );
    }

	/**
	 * 获取7日内的订单相关数据
	 */
	public function getsevendays(){
		$city_id   = (int)$this->request->post('city_id', 0);
		$where = [];
		$where['status'] = array('egt',2);
		if( $city_id > 0 ){
			$where['city_id'] = $city_id;
		}
			
		//订单总额统计
		$OrderMoneySevenArr = LihuaOrder::whereTime('create_time', '-9 day')
			->where(array('status' => array('egt',2)))
			->field("FROM_UNIXTIME(create_time,'%Y-%m-%d') AS dt,count(id) AS num, sum(order_amount) as amount")
			->group('dt')
			->select();
			
		if($OrderMoneySevenArr){
			$this->success('OK', ['sevenData' => $OrderMoneySevenArr ] );
		}else{
			$this->error('获取7天内每日订单量失败');
		}
    }
    
    /*
     * 根据购物车获取商品相关信息
     */
    public function getCartOrderInfo(){
        $this->request->filter('trim,strip_tags');
        $store_id   = (int)$this->request->post('store_id', 0);//门店ID
        $goods_nums   = $this->request->post('goods_nums', '');//商品及数量
        if (!$goods_nums)   $this->error('请选择商品');
        if (!$store_id)   $this->error('该地区暂不支持订购');
        $goods_nums = json_decode($goods_nums, true);
        $goods = \app\common\model\goods\LihuaGoods::getCartGoodsList($store_id, $goods_nums);
        $this->success('OK', $goods);
    }
	
    /**
     * 订单列表
     *
     * @ApiMethod   (POST)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="city_id", type="int", required=false, description="城市ID")
     * @ApiParams   (name="page", type="int", required=true, description="当前页，默认第1页")
     * @ApiParams   (name="page_size", type="int", required=false, description="每页条数，默认10条")
     * @ApiReturn   ({"code":1,"msg":"OK","time":"1573374133","data":{"page":1,"total":7,"page_size":10,"total_page":1,"list":[{"id":201,"sn":"1911434880963790","time":"2019-11-09 16:04","status":1,"status_text":"等待支付","goods":[{"id":1460,"name":"25元 秘制翅中饭","short_name":"翅中饭","price":25,"pic":"http://image.lihua.com/images/newweb/2015/11/thumb_56596b3ce997d.jpg","num":1,"num_price":25},{"id":2210,"name":"28元 糖醋排骨饭","short_name":"排骨+赠饮","price":28,"pic":"http://image.lihua.com/images/newweb/2016/04/thumb_57144be324714.jpg","num":1,"num_price":28}],"discount":10,"amount":48},{"id":152,"sn":"191023421430910","time":"2019-10-14 10:49","status":0,"status_text":"订单已取消","goods":[{"id":2911,"name":"促销38元套餐","short_name":"牛肉促","price":35,"pic":"http://image.lihua.com/images/newweb/2016/01/thumb_56a5dcdf0a1e0.JPG","num":1,"num_price":35}],"discount":0,"amount":23}]}})
     */
    public function index()
    {
        $city_id    = (int)$this->request->post('city_id', 0);
        $status     = (int)$this->request->post('status', 0);
        $page       = max(1, (int)$this->request->post('page'));
        $page_size  = (int)$this->request->post('page_size') ? : 10;
        $type       = (int)$this->request->post('type', 0);
        $data       = [
            'page'       => $page,
            'total'      => 0,
            'page_size'  => $page_size,
            'total_page' => 0,
            'list'       => []
        ];

        $where['user_id'] = $this->auth->id;
        if ($city_id > 0) $where['city_id'] = $city_id;

        // 订单状态:0=已取消,1=待支付,2=待确认,3=待分配,4=待派送,5=派送中,6=已完成
        if($type==0) $where['status'] = ['IN',[0, 1, 2, 3, 4, 5, 6]];
        if($type==1) $where['status'] = 1;
        if($type==2) $where['status'] = ['IN',[2, 3, 4, 5]];
        if($type==3) $where['status'] = 6;
        if($type==4) $where['status'] = 0;
        $total = LihuaOrder::where($where)->count();
        if ($total) {
            $data['total']      = $total;
            $data['total_page'] = ceil($total/$page_size);
            $list = LihuaOrder::where($where)->field('id,sn,order_amount,discount,status,create_time,doorshop,wallet_given_fee,office_id')
                ->order('id', 'desc')->page($page, $page_size)->select();
            $data['list'] = $this->reOrderList($list);
        }

        $this->success('OK', $data);
    }

    /**
     * 写字楼订单列表
     *
     * @ApiMethod   (POST)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="city_id", type="int", required=false, description="城市ID")
     * @ApiParams   (name="page", type="int", required=true, description="当前页，默认第1页")
     * @ApiParams   (name="page_size", type="int", required=false, description="每页条数，默认10条")
     * @ApiReturn   ({"code":1,"msg":"OK","time":"1573374133","data":{"page":1,"total":7,"page_size":10,"total_page":1,"list":[{"id":201,"sn":"1911434880963790","time":"2019-11-09 16:04","status":1,"status_text":"等待支付","goods":[{"id":1460,"name":"25元 秘制翅中饭","short_name":"翅中饭","price":25,"pic":"http://image.lihua.com/images/newweb/2015/11/thumb_56596b3ce997d.jpg","num":1,"num_price":25},{"id":2210,"name":"28元 糖醋排骨饭","short_name":"排骨+赠饮","price":28,"pic":"http://image.lihua.com/images/newweb/2016/04/thumb_57144be324714.jpg","num":1,"num_price":28}],"discount":10,"amount":48},{"id":152,"sn":"191023421430910","time":"2019-10-14 10:49","status":0,"status_text":"订单已取消","goods":[{"id":2911,"name":"促销38元套餐","short_name":"牛肉促","price":35,"pic":"http://image.lihua.com/images/newweb/2016/01/thumb_56a5dcdf0a1e0.JPG","num":1,"num_price":35}],"discount":0,"amount":23}]}})
     */
    public function office_list()
    {
        $city_id    = (int)$this->request->post('city_id', 0);
        $status     = (int)$this->request->post('status', 0);
        $page       = max(1, (int)$this->request->post('page'));
        $page_size  = (int)$this->request->post('page_size') ? : 10;
        $type       = (int)$this->request->post('type', 0);
        $data       = [
            'page'       => $page,
            'total'      => 0,
            'page_size'  => $page_size,
            'total_page' => 0,
            'list'       => []
        ];

        $where['user_id'] = $this->auth->id;
        $where['office_id'] = ['>', 0];
        if ($city_id > 0) $where['city_id'] = $city_id;

        // 订单状态:0=已取消,1=待支付,2=待确认,3=待分配,4=待派送,5=派送中,6=已完成
        if($type==0) $where['status'] = ['IN',[0, 1, 2, 3, 4, 5, 6]];
        if($type==1) $where['status'] = 1;
        if($type==2) $where['status'] = ['IN',[2, 3, 4, 5]];
        if($type==3) $where['status'] = 6;
        if($type==4) $where['status'] = 0;
        $total = LihuaOrder::where($where)->count();
        if ($total) {
            $data['total']      = $total;
            $data['total_page'] = ceil($total/$page_size);
            $list = LihuaOrder::where($where)->field('id,sn,order_amount,discount,status,create_time,doorshop,wallet_given_fee, office_id, office_stoptime')
                ->order('id', 'desc')
                ->page($page, $page_size)
                ->select();
            $data['list'] = $this->reOrderList($list);
        }

        $this->success('OK', $data);
    }

    /**
     * 游客订单列表
     *
     * @ApiMethod   (POST)
     * @ApiParams   (name="sn", type="string", required=true, description="订单号组")
     * @ApiReturn   ({"code":1,"msg":"OK","time":"1573374469","data":{"list":[{"id":4,"sn":"190973870676869","time":"2019-09-06 16:46","status":0,"status_text":"订单已取消","goods":[{"id":1464,"name":"20元 蜜汁酱鸭饭","short_name":"酱鸭饭","price":20,"pic":"http://image.lihua.com/images/newweb/2018/03/thumb_5aae02a0dc1eb.jpg","num":1,"num_price":20},{"id":1654,"name":"原味奶茶","short_name":"奶茶","price":5,"pic":"http://image.lihua.com/images/newweb/2015/12/thumb_5660ef2ca54ca.jpg","num":1,"num_price":5},{"id":1659,"name":"骨肉相连","short_name":"骨肉相连","price":2,"pic":"http://image.lihua.com/images/newweb/2015/12/thumb_5660f1354f4ec.jpg","num":2,"num_price":4}],"discount":0,"amount":33},{"id":3,"sn":"190969600627237","time":"2019-09-06 16:41","status":1,"status_text":"等待支付","goods":[{"id":2035,"name":"板栗焖鸡拼外婆菜套餐","short_name":"板栗焖鸡拼外婆菜","price":20,"pic":"http://image.lihua.com/images/newweb/2015/12/thumb_566f632f56520.jpg","num":3,"num_price":60}],"discount":0,"amount":66}]}})
     */
    public function guestIndex()
    {
        $sn = $this->request->post('sn', '');
        if (!$sn) $this->error('参数错误');

        $list = LihuaOrder::whereIn('sn', $sn)->field('id,sn,order_amount,discount,status,create_time')
            ->order('id', 'desc')->select();

        $data = ['list' => $this->reOrderList($list)];
        $this->success('OK', $data);
    }

    /**
     * 重新组织订单列表数据
     *
     * @ApiInternal
     * @param array $list 订单列表
     * @return array
     */
    public function reOrderList($list = [])
    {
        $data = [];
        if ($list) {
            $ids    = array_column($list, 'id');
            $goods  = LihuaOrderGoods::ordersGoodsList($ids);
            $status = LihuaOrder::getStatusList();
            foreach ($list as $k => $v) {
                $data[] = [
                    'id'          => $v['id'],
                    'sn'          => $v['sn'],
                    'time'        => date("Y-m-d H:i", $v['create_time']),
                    'status'      => $v['status'],
                    'status_text' => isset($status[$v['status']]) ? $status[$v['status']] : '',
                    'goods'       => isset($goods[$v['id']]) ? $goods[$v['id']] : [],
                    'discount'    => round($v['discount'], 2),
                    'amount'      => round($v['order_amount'], 2),
                    'doorshop'    => isset($v['doorshop']) ? $v['doorshop'] : 0,
                    'office_id'   => $v['office_id'],
                    'wallet_given_fee'  => isset($v['wallet_given_fee']) ? $v['wallet_given_fee'] : 0,
                ];
            }
        }
        return $data;
    }

    /**
     * 订单详情
     *
     * @ApiMethod   (POST)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token,游客不传")
     * @ApiParams   (name="sn", type="int", required=true, description="订单号")
     * @ApiReturn   ({"code":1,"msg":"OK","time":"1573374575","data":{"id":65,"sn":"190952212390507","user_id":3,"city_id":3,"city_name":"常州","store_id":18,"store_name":"湖塘","consignee":"吴大帝","mobile":"13961259813","address":"中源大厦502室","lng":"119.949513","lat":"31.731623","packing_fee":2,"deliver_fee":3,"enough_name":"","enough_fee":10,"bonus_name":"10元新人红包","bonus_fee":10,"deliver_time":"2019-09-23 12:00:00","tableware":1,"invo_type":1,"invo_title":"吴大帝","invo_taxno":"","remark":"","goods_amount":53,"original_amount":58,"order_amount":38,"discount":20,"add_time":"2019-09-23 16:55:05","platform":"app","pay_type":"支付宝支付","pay_status":0,"pay_time":null,"confirm_time":null,"store_time":null,"rider_time":null,"finish_time":null,"cancel_time":null,"status":1,"create_time":1569228905,"update_time":1573202623,"status_text":"等待支付","goods":[{"id":1460,"name":"25元 秘制翅中饭","short_name":"翅中饭","price":25,"pic":"http://image.lihua.com/images/newweb/2015/11/thumb_56596b3ce997d.jpg","num":1,"num_price":25},{"id":2210,"name":"28元 糖醋排骨饭","short_name":"排骨+赠饮","price":28,"pic":"http://image.lihua.com/images/newweb/2016/04/thumb_57144be324714.jpg","num":1,"num_price":28}]}})
     */
    public function detail()
    {
        $sn  = $this->request->post('sn', '');
        $map = ['sn' => $sn];
        if ($this->token) $map['user_id'] = $this->auth->id;
        $row = LihuaOrder::get($map);
        if (!$row) $this->error('非法操作');

        //查询是否参加了某个促销活动
        $orderAct = LihuaOrderActivity::where(['order_sn'=> $sn])->select();
        $row['packing_fee']     = round($row['packing_fee'], 2);
        $row['deliver_fee']     = round($row['deliver_fee'], 2);
        $row['enough_fee']      = round($row['enough_fee'], 2);
        $row['bonus_fee']       = round($row['bonus_fee'], 2);
        $row['discount']        = round($row['discount'], 2);
        $row['goods_amount']    = round($row['goods_amount'], 2);
        $row['original_amount'] = round($row['original_amount'], 2);
        $row['order_amount']    = round($row['order_amount'], 2);
        if(count($orderAct)>0){
            foreach ($orderAct as $k => $v) {
                if($v['type']==0){
                    $orderAct[$k]['name'] = '第二份半价';
                }
                if($v['type']==1){
                    $orderAct[$k]['name'] = '限时促销';
                }
            }
        }
        $row['orderAct']        = $orderAct;
        $statusArr  = LihuaOrder::getStatusList();
        $row['status_text'] = $statusArr[$row['status']];

        $payTypeArr = LihuaCity::getPayTypeList();
        $row['pay_type_num'] = $row['pay_type'];
        $row['pay_type'] = $row['pay_type'] > 0 ? $payTypeArr[$row['pay_type']] : '';

        //获取城市详情
        $city = LihuaCity::getCityInfo($row['city_id']);
        $res_invoice = '';
        $cityname = $city['city_name'];
        if($cityname=='上海'||$cityname=='苏州'||$cityname=='广州'){
            $res_invoice = "发票";
        }
        if($cityname=='常州'||$cityname=='无锡'||$cityname=='南京'||$cityname=='北京'){
            $res_invoice = "电子发票";
        }
        
        $goods = LihuaOrderGoods::ordersGoodsList([$row['id']]);
        $row['goods'] = $goods[$row['id']];
        $row['res_invoice'] = $res_invoice;
        $this->success('OK', $row);
    }

    /**
     * 生成退单记录
     **/
    public function createLihuaRefund($order, $status, $applyreason)
    {
        $havecreated = LihuaRefund::where([ 'order_sn' => $order['sn'] ])->find();
        if($havecreated){
            return '该订单已经申请过退款了';
        }else{
            $order_amount = $order['order_amount'];

            $data = [
                'order_sn'          => $order['sn'],
                'price'             => $order['order_amount'],
                'wallet_given_fee'  => $order['wallet_given_fee'],
                'wallet_money_pay'  => $order['wallet_money_pay'],
                'status'            => $status,
                'user_id'           => $order['user_id'],
                'mobile'            => $order['mobile'],
                'city_id'           => $order['city_id'],
                'city_name'         => $order['city_name'],
                'create_time'       => time(),
                'update_time'       => time(),
                'consignee'         => $order['consignee'],
                'applyreason'       => $applyreason, // 申请理由
                'refusereason'      => '', // 拒绝理由
                'pay_type'          => $order['pay_type'],//支付方式
            ];
            $create = LihuaRefund::create($data);
            return !!$create;
        }
    }

    /*查看退款进度*/
    public function chickRefund(){
        $sn = $this->request->post('sn'); //订单id
        if (!$sn) $this->error('参数错误');
        $data = LihuaRefund::where(['order_sn'=>$sn])->find();
        $press = array();
        if($data){
            if($data['status']==0){
                $press[] = '退款申请已经成功';
                $press[] = '等待客服审核处理...';
            }
            if($data['status']==1){
                $press[] = '退款申请已经成功';
                $press[] = '审核已通过';
                $press[] = '退款申请已完成';
                $press[] = '查看微信到账情况';
            }
            if($data['status']==2){
                $press[] = '退款申请已经成功';
                $press[] = '审核通过未通过';
                $press[] = '拒绝理由:'.$data['refusereason'];
            }
            if($data['status']==3){
                $press[] = '退款申请已经成功';
                $press[] = '审核已通过';
                $press[] = '1到2个工作日会退款到账';
            }
        }
        $this->success('OK', ["list"=>$press]);
    }

    // 拒绝退款
    public function refuseapply(){
        $sn = $this->request->post('sn', ''); //订单编号
        $refusereason = $this->request->post('refusereason', '');//拒绝理由
        if (!$sn || !$refusereason) $this->error('参数错误');
        $order = LihuaOrder::getBySn($sn);
        $updata_refund = LihuaRefund::where([ 'order_sn'=>$sn ])->update([ 'status'=>2, 'refusereason'=> $refusereason ]);
        if($updata_refund){
            $this->success('OK');
        }else{
            $this->error('error');
        }
    }

    // 抄送给财务退款
    public function refuse_financial(){
        $sn = $this->request->post('sn', ''); //订单编号
        if (!$sn) $this->error('参数错误');
        $order = LihuaOrder::getBySn($sn);
        $updata_refund = LihuaRefund::where([ 'order_sn'=>$sn ])->update([ 'status'=>3 ]);
        if($updata_refund){
            $this->success('OK');
        }else{
            $this->error('error');
        }
    }

    // 用户主动点击完成订单
    public function finish(){
        $sn = $this->request->post('sn', '');
        if (!$sn) $this->error('参数错误');
        $order = LihuaOrder::getBySn($sn);
        if (!$order) $this->error('非法操作');
        //必须完成了支付的情况下才能点击完成订单
        $order->finish_time = date('Y-m-d H:i:s');
        $order->status = 6;
        $s = $order->save();
        $this->success('OK', $s);
    }

    /**
     * 退款接口
     * @ApiMethod   (POST)
     * @ApiParams   (name="sn", type="string", required=true, description="订单号")
     * @ApiReturn   ({"code":1,"msg":"OK","time":"1568696762","data":{}})
     * 1=支付宝支付,2=微信支付,3=丽华钱包,6=银联微信,7=云闪付
     * */
    public function queryRefundReq()
    {
        $sn = $this->request->post('sn', '');//订单sn
        if (!$sn) $this->error('参数错误');
        $order = LihuaOrder::getBySn($sn);
        if (!$order) $this->error('非法操作');
        $city_arr = ['',"bj","sh","cz","nj","sz","wx","gz"];
        $city_s = $city_arr[$order['city_id']];
        
    }

    /**
	 * 钱包退款3
	 * **/
	public function wallet_refund($sn = '', $price = 0)
	{
		//这里需要调用钱包系统退款接口进行退款处理
		$data = [ 'sn' => $sn, 'refund_price' => $price ];
		try {
			$url = "http://qianbao.lihua.com/api/wallet/refund_order";
			$ret = Http::post($url, $data);
        } catch (\Exception $e) {
			$this->error($e);
            return false;
        }
        return true;
	}

    /**
     * 微信小程序取消订单
     *
     * @ApiMethod   (POST)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token,游客不传")
     * @ApiParams   (name="sn", type="string", required=true, description="订单号")
     * @ApiReturn   ({"code":1,"msg":"OK","time":"1568696762","data":{}})
     */
    public function cancel()
    {
        $sn = $this->request->post('sn', '');
        $applyreason = $this->request->post('applyreason', '');//退单理由
        if (!$sn) $this->error('参数错误');
        $order = LihuaOrder::getBySn($sn);
        if (!$order) $this->error('非法操作');
        $city_arr = ['',"bj","sh","cz","nj","sz","wx","gz"];
        $city_s = $city_arr[$order['city_id']];
        if ($this->token) {
            if ($order->user_id != $this->auth->id) $this->error('无权操作');
        } else {
            if ($order->user_id != 0) $this->error('无权操作');
        }
        // 未支付的状态下退单
        if ($order->status == 1) {
            /**
             * 这里需要判断是否有部分支付的情况
             * 首先需要计算出丽华钱包支付部分的金额
             * **/ 
            $wallet_pay_money = bcadd(floatval($order->wallet_money_pay) , floatval($order->wallet_given_fee), 2);
            if($wallet_pay_money>0){
                //这里需要对钱包进行退款
                $s = $this->wallet_refund($sn, $wallet_pay_money);
                $b = $s;
            }
            
            $order->cancel_time = date('Y-m-d H:i:s');
            $order->status = 0;
            $order->save();

            // 恢复用户红包
            if ($order->bonus_fee > 0) {
                LihuaUserbonus::update(['status' => 0, 'order_sn' => ''], ['user_id' => $this->auth->id, 'order_sn' => $sn]);
            }
            // 如果使用的现金抵扣券
            if ($order->vouchers_sn != '') {
                LihuaVouchers::update(['status' => 0, 'order_sn' => '', 'update_time'=> time()], ['user_id' => $this->auth->id, 'sn' => $order->vouchers_sn]);
            }
            
            $this->success('OK');
        }else{
            $this->error('error');

            /*
             * 已经支付的状态下
             * 1、5分钟之内的订单，订单取消，通知客服退单，直接退款到客户微信
             * 2、5分钟之后还没送达的订单，订单取消，通知客服退单，生成一条退款申请
             * 3、5分钟之后已经完成的订单，只能发起退款申请，客服需要特俗处理
             */
            // 5分钟之内直接退款退单
            $dtime = strtotime($order->pay_time);
            $now = time();
            $fivetime = 5*60;
            $infivetime = (($now - $dtime) <= $fivetime);// 是否在5分钟之内
            /*
             * 微信中的已支付而且是在线支付方式，肯定是微信支付
             * **/
            if ($order->pay_status == 1) {
                // 已支付状态下
                if( ($order->pay_type == 6 || $order->pay_type == 7) && $order->order_amount>0 ){
                    // 5分钟之内
                    if($infivetime){
                        // 直接退款
                        $api = "https://newapp.lihua.com/api/pay/unionpay_wx_queryRefund?sn=".$order['sn'];
                        $res = Http::get($api);
                        $ret = json_decode($res, true);
                        if($ret['code']!=1){ $this->error($ret['msg']); };
                        $order->cancel_time = date('Y-m-d H:i:s');
                        $order->status = 0;
                        $order->save();
                        $api2 = "http://cz.lihua.com/index.php?s=/WebApi/message/type/20/city/".$city_s."/ordersn/".$order['sn'].".html";
                        $res2 = Http::get($api2);
                        $createRefund = $this->createLihuaRefund($order, 1, $applyreason);
                        $this->success('5分钟之内自动提款',['a'=>$res,'b'=>$res2]);
                    }else{
                        // 订单还未完成的情况下
                        if($order->status!=6){
                            // 取消订单
                            $order->cancel_time = date('Y-m-d H:i:s');
                            $order->status = 0;
                            $order->save();
                            // 给客服发送取消订单的通知
                            $api2 = "http://cz.lihua.com/index.php?s=/WebApi/message/type/20/city/".$city_s."/ordersn/".$order['sn'].".html";
                            $res2 = Http::get($api2);
                            $createRefund = $this->createLihuaRefund($order, 0, $applyreason);
                            $this->success('5分钟后需要客服审核',['a'=>$createRefund,'b'=>$res2]);
                            // 客服接受到退单信息后，需要审核并且通知分公司停止送餐，审核完毕的情况下资金原路返还
                        }else{
                            // 订单已完成的情况下也可以申请退款，但是订单状态不可变
                            $api2 = "http://cz.lihua.com/index.php?s=/WebApi/message/type/20/city/".$city_s."/ordersn/".$order['sn'].".html";
                            $res2 = Http::get($api2);
                            $createRefund = $this->createLihuaRefund($order, 0, $applyreason);
                            $this->success('订单已完成的情况下退款',['a'=>$createRefund,'b'=>$res2]);
                        }
                    }
                }else{
                    // 微信支付 支付宝支付 丽华钱包 退款
                    if($order->pay_type==2||$order->pay_type==1||$order->pay_type==3){
                        $this->error('功能维护中,退单请联系客服4008800400');
                        $applyreason = "[财务手动退款 无需这里处理]".$applyreason;
                        // 订单还未完成的情况下
                        if($order->status!=6){
                            // 取消订单
                            $order->cancel_time = date('Y-m-d H:i:s');
                            $order->status = 0;
                            $order->save();
                            // 给客服发送取消订单的通知
                            $api2 = "http://cz.lihua.com/index.php?s=/WebApi/message/type/20/city/".$city_s."/ordersn/".$order['sn'].".html";
                            $res2 = Http::get($api2);
                            $createRefund = $this->createLihuaRefund($order, 0, $applyreason);
                            $this->success('申请退款，需要财务手动退款',['a'=>$createRefund,'b'=>$res2]);
                            // 客服接受到退单信息后，需要审核并且通知分公司停止送餐，审核完毕的情况下资金原路返还
                        }else{
                            // 订单已完成的情况下也可以申请退款，但是订单状态不可变
                            $api2 = "http://cz.lihua.com/index.php?s=/WebApi/message/type/20/city/".$city_s."/ordersn/".$order['sn'].".html";
                            $res2 = Http::get($api2);
                            $createRefund = $this->createLihuaRefund($order, 0, $applyreason);
                            $this->success('申请退款，需要财务手动退款',['a'=>$createRefund]);
                        }
                    }
                    $this->error('功能维护中,退单请联系客服4008800400');
                }
            }else {
                // 未支付状态下
                if($order->pay_type == 4 || $order->pay_type == 5){
                    $this->error('功能维护中,退单请联系客服4008800400');
                    $order->cancel_time = date('Y-m-d H:i:s');
                    $order->status = 0;
                    $order->save();
                    if ($order->bonus_fee > 0 && $this->token) {// 恢复用户红包
                        LihuaUserbonus::update(['status' => 0, 'order_sn' => ''], ['user_id' => $this->auth->id, 'order_sn' => $sn]);
                    }
                    $api2 = "http://cz.lihua.com/index.php?s=/WebApi/message/type/20/city/".$city_s."/ordersn/".$order['sn'].".html";
                    $res2 = Http::get($api2);
                    $this->success('货到付款或贵宾卡退单',['b'=>$res2]);
                }else{
                    $this->error('功能维护中,退单请联系客服4008800400');
                }
            }
            
        }
        $this->error('取消失败');
    }

    //2分钟之内取消订单
    public function cancel_intime()
    {

    }

    /**后台取消订单操作
     * 
     */
    public function cancel_admin()
    {
        //传参
        $sn = $this->request->request('sn', '');
        $applyreason = $this->request->request('refusereason', '');//退单理由
        if (!$sn || !$applyreason) $this->error('参数错误');
        //获取订单详情
        $order = LihuaOrder::getBySn($sn);
        if (!$order) $this->error('非法操作');
        //获取城市代码
        $city_arr = ['',"bj","sh","cz","nj","sz","wx","gz"];
        $city_s = $city_arr[$order['city_id']];
        if($order->status==1){
            //此时订单未下单成功，此时只能客户自己取消
            $this->error('此订单未下单成功，客户可以自己取消');
        }
        if($order->status==0){
            $this->error('订单已被取消');
        }
        if($order->status>=2){
            //定义退单详情
            $cancel_obj =[
                'havecancel' => false,//是否已经被取消
                'createrefund' => false,//是否生成了退款记录
                'havesendmessage' => false,//是否推送了信息给送餐系统，通知客服人员进行退单
            ];
            /*
             * 订单已经成功下单
             * 此时只能通过客服电话进行退单
             * 1、首先要查询订单是否被送餐系统拉取，如果已经进入派送流程，需要对派单系统进行退单处理
             * 2、如果支付方式为在线支付(1=支付宝支付,2=微信支付,3=丽华钱包,6=银联微信,7=云闪付)生成退款记录
             */
            //第一步先取消订单:此处需要客户和客服沟通后才能点击取消
            $order->cancel_time = date('Y-m-d H:i:s');
            $order->status = 0;
            $cancel_res = $order->save();
            $cancel_obj['havecancel'] = !!$cancel_res;

            // 恢复用户红包
            if ($order->bonus_fee > 0) {
                LihuaUserbonus::update(['status' => 0, 'order_sn' => ''], ['user_id' => $order->user_id, 'order_sn' => $sn]);
            }
            // 如果使用的现金抵扣券
            if ($order->vouchers_sn != '') {
                LihuaVouchers::update(['status' => 0, 'order_sn' => '', 'update_time'=> time()], ['user_id' => $order->user_id, 'sn' => $order->vouchers_sn]);
            }


            //第二步判断是否需要生成退款记录
            $can_cancel_type = array(1, 2, 3, 6, 7);
            if (in_array($order->pay_status, $can_cancel_type)){
                //生成退单记录
                $createRefund = $this->createLihuaRefund($order, 0, $applyreason);
                $cancel_obj['createrefund'] = !!$createRefund;
            }
            //第三步通知到送餐系统，进行退单处理
            $api = "http://cz.lihua.com/index.php?s=/WebApi/message/type/20/city/".$city_s."/ordersn/".$order['sn'].".html";
            $res = Http::get($api);
            $res_o = json_decode($res, true);
            $cancel_obj['havesendmessage'] = ($res_o['code']=='ok');
            Log::record('[cancel_order::sendmessage->'.$res_o['code'], 'info');
            $this->success('ok', [ 'status'=>$cancel_obj, 'data'=>$res, 'api'=>$api ]);
        }
    }

    /**
     * 
     * 已完成的订单发起 退款申请
     * */
    public function sendRefundRes(){
        $sn = $this->request->post('sn', '');//订单编号
        $applyreason = $this->request->post('applyreason', '');//备注
        $order = LihuaOrder::getBySn($sn);
        $createRefund = $this->createLihuaRefund($order, 0, $applyreason);
        $this->success('订单已完成的情况下退款',['a'=>$createRefund]);
    }

    /**订单状态进度
     * 
     *
     * @ApiMethod   (POST)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token，游客不传")
     * @ApiParams   (name="sn", type="string", required=true, description="订单号")
     * @ApiReturn   ({"code":1,"msg":"OK","time":"1568740242","data":{"list":[{"status":"订单提交成功","time":"09-06 16:46","tips":"","pass":1,"ing":0},{"status":"订单已取消","time":"09-17 21:42","tips":"你取消了订单","pass":1,"ing":0}]}})
     */
    public function status()
    {
        $sn = $this->request->post('sn');
        if (!is_numeric($sn)) $this->error('参数错误');

        $user_id = $this->token ? $this->auth->id : 0;
        $list = LihuaOrder::getOrderProcess($sn, $user_id);
        $this->success('OK', ['list' => $list]);
    }

    public function status_office()
    {
        $sn = $this->request->post('sn');
        if (!$sn) $this->error('参数错误');

        $user_id = $this->token ? $this->auth->id : 0;
        $list = LihuaOrder::getOrderProcess($sn, $user_id);
        $this->success('OK', ['list' => $list]);
    }

    /**
     * 评价订单
     *
     * @ApiMethod   (POST)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求Token，游客不传")
     * @ApiParams   (name="sn", type="string", required=true, description="订单号")
     * @ApiParams   (name="content", type="string", required=false, description="评价内容")
     * @ApiParams   (name="goods_score", type="string", required=true, description="商品评分")
     * @ApiParams   (name="courier_score", type="string", required=true, description="骑手评分")
     * @ApiParams   (name="service_score", type="string", required=true, description="服务评分")
     * @ApiParams   (name="pics", type="string", required=false, description="评价图片")
     * @ApiReturn   ({"code":1,"msg":"OK","time":"1571479126","data":{}})
     */
    public function comment()
    {
        $sn = $this->request->post('sn');
        $content = $this->request->post('content', '');
        $goods_score   = (int)$this->request->post('goods_score', 0);
        $courier_score = (int)$this->request->post('courier_score', 0);
        $service_score = (int)$this->request->post('service_score', 0);
        $pics = $this->request->post('pics', '');

        if (!is_numeric($sn)) $this->error('参数错误');
        if ($goods_score == 0 || $courier_score == 0 || $service_score == 0) $this->error('你太懒了，请打个分');

        $row = LihuaOrder::where('sn', $sn)->field('id,city_id,store_id')->find();
        if (!$row) $this->error('非法操作');

        if (mb_strlen($content) > 200) $this->error('评价内容已超200字限制');

        $data = [
            'city_id'       => $row['city_id'],
            'store_id'      => $row['store_id'],
            'user_id'       => (int)$this->auth->id,
            'nickname'      => $this->auth->nickname ? : '',
            'order_id'      => $row['id'],
            'order_sn'      => $sn,
            'content'       => $content,
            'goods_score'   => $goods_score,
            'courier_score' => $courier_score,
            'service_score' => $service_score,
            'pics'          => $pics,
            'create_time'   => time(),
        ];

        try {
            \app\common\model\LihuaComment::create($data);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }

        $this->success('OK');
    }

}
